﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using ExamUtils;

namespace ExamCommon
{
    public class SocketHelper
    {
        /// <summary>
        /// 发送message消息
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool SendMessage(Socket socket, Message msg)
        {
            // 防止空指针
            if (socket == null || msg == null)
            {
                return false;
            }
            // 初始化消息来源和目的地
            msg.initEndPoint(socket);
            try
            {
                // 将message对象转换为byte[]用于网络传输
                byte[] byteArr = Converter.ObjectToBytes(msg);
                // 发送消息
                socket.Send(byteArr);
            }
            catch (Exception ex)
            {
                Console.WriteLine("error: " + msg.fromEndPoint.ToString() + " ----> "
                    + msg.toEndPoint.ToString() + "发送消息时出现异常: " + ex.Message);
            }
            return true;
        }

        /// <summary>
        /// 接收message消息
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        public static Message ReceiveMessage(Socket socket)
        {
            // 防止空指针
            if (socket == null)
            {
                return null;
            }
            Message message = null;
            try
            {
                // 接受发送来的消息
                byte[] tempBuffer = new byte[1024 * 1024 * 1];  // tempBuffer大小为1M, 这里是否需要优化? 
                                                                // 接收消息, 返回实际接受的字节数
                int n = socket.Receive(tempBuffer);
                // 如果字节数为0 则说明客户端被关闭
                if (n == 0)
                {
                    return null;
                }
                // 取出有效的字节数组
                byte[] buffer = tempBuffer.Take(n).ToArray();
                // 将字节数组转化为object对象
                object msg = Converter.BytesToObject(buffer);
                // 将object转化为message对象
                message = msg as Message;
            }
            catch (Exception ex)
            {
                Console.WriteLine("error: 接受消息发生异常: " + ex.Message);
            }
            return message;
        }
    }
}
